﻿package com.skin {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.system.ApplicationDomain;

	/**
	 * 获取皮肤的定义和返回对象 ,采用多皮肤进行选择
	 * @author pethan
	 *
	 */
	public class SkinManage {
		private var skins:Vector.<MovieClip>;

		public function SkinManage(se:SingletonEnforcer){
			if (se == null){
				throw new Error('请使用单例');
			}
			skins = new Vector.<MovieClip>();
		}
		private static var _instance:SkinManage;

		public static function getInstance():SkinManage {
			if (_instance == null)
				_instance = new SkinManage(new SingletonEnforcer());
			return _instance;
		}

		public function set skinSwf(movie:MovieClip):void {
			if (this.skins.indexOf(movie) == -1){ /*不存在此皮肤,就添加这样的皮肤上去*/
				this.skins.push(movie);
			}
		}
		/**
		 * 得到一个类定义
		 * @param fromCurAsset	true 	先从公共定义皮肤取出来(若未找到定义就从当前asset取出)
		 * 						false	从当前asset取出
		 * @param fromSwc  true为从Swc加载类定义,flase为从swf加载类定义
		 */
		public function getClass(className:String):Class {
			return getDomainClass(className) as Class;
		}

		//获取类的定义,如果皮肤有定义先从皮肤获取定义,如果皮肤的swf不存在此定义就从本身的swc返回
		private function getDomainClass(className:String):Class {
			var ret:Class;
			//先从多个皮肤库中进行查找
			for (var i:int = 0; i < this.skins.length; i++){
				if (this.skins[i].loaderInfo.applicationDomain.hasDefinition(className)){
					ret = this.skins[i].loaderInfo.applicationDomain.getDefinition(className) as Class;
					break;
				}
			}
			if (ret == null && ApplicationDomain.currentDomain.hasDefinition(className)){
				ret = ApplicationDomain.currentDomain.getDefinition(className) as Class;
			}
			return ret;
		}

		/**
		 * 获取位图数据
		 * @param className 类名
		 * @param fromSwc  true为从Swc加载类定义,flase为从swf加载类定义
		 * @return bitmapdata
		 *
		 */
		public function getBitmapData(className:String):BitmapData {
			var bitmapClass:Class = getDomainClass(className) as Class;
			return new bitmapClass(0, 0);
		}

		/**
		 * 返回显示图片
		 * @param className  类名
		 * @return  Bitmap
		 *
		 */
		public function getBitmap(className:String):Bitmap {
			var bitmap:Bitmap = new Bitmap(getBitmapData(className));
			return bitmap;
		}

		/**
		 * 返回swf里面的影片数据
		 * @param className
		 * @param fromSwc  true为从Swc加载类定义,flase为从swf加载类定义
		 * @return
		 *
		 */
		public function getMovieClip(className:String):MovieClip {
			var movieClip:Class = getDomainClass(className) as Class;
			return new movieClip();
		}
	}
}

class SingletonEnforcer {
}